﻿import sys
import urllib2
import logging
import json
import platform
from uuid import *
from diskinfo import *
from raminfo import *
from osinfo import *
from cpuinfo import *
from ifinfo import *
import socket

API_ADDR = '10.32.174.152:8080' #API url
ifname = "eth0"  #Network Interface

logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='cmdb.log',
                filemode='w')

console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

def print_dict(result):
    for k, v in result.iteritems():
        print '%s : %s' % (k, v)

def handle_result(result):
    logging.info(result)

def http_post(url, data):
    headers = {
        "Content-Type": "application/json",
        "Accept-Charset": "utf-8"
    }
    request = urllib2.Request(url, json.dumps(data), headers)
    try:
        response = urllib2.urlopen(request, timeout=10)
    except urllib2.URLError, e:
        logging.error(e)
    result = json.loads(response.read())
    return handle_result(result)

def send_cmdb_info(dict):
    url = "http://%s/services/IServerInfoVenusService/syncServerInfo" % API_ADDR
    data = {
            "serverInfo": dict
    }
    logging.info(data)
    return http_post(url, data)

if __name__ == '__main__':
    dict = {}
    meminfo = meminfo()
    osversion = osversion()
    cpuinfo = CPUinfo()
    diskinfo = get_total_disk()
    sysinfo = parseDmi(parseData(getDmi()))
    osname = osname()
    uuid = sysinfo['UUID']
    sn = sysinfo['sn']
    ip = ip(ifname)
    mac = mac(ifname)
    type = VirPhy(parseDmi(parseData(getDmi())))
    dict['kernelVersion'] = platform.platform()
    dict['hostName'] = socket.gethostname()
    dict['osVersion'] = osversion
    dict['remSize'] = meminfo
    dict['cpu'] = cpuinfo[1]
    dict['cpuNum'] = cpuinfo[0]
    dict['diskSize'] = diskinfo
    dict['type'] = type
    dict['mac'] = mac
    dict['privateIp'] = ip
    dict['uuid'] = uuid
    dict['idc'] = "jinqiao"
    dict['sn'] = sn
    dict['osName'] = osname
#    print dict
    send_cmdb_info(dict) 
    

